import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from "axios";
import type { IConfig } from "./type";
import { ACCESS_TOKEN, CURRENT_ADMIN } from "@/store/mutation-types";
import { storage } from "@/utils/lib/Storage";
import { useRouter } from "vue-router";
const router = useRouter();
/**
 * @description:  axios模块
 */
class VAxios {
	private axiosInstance: AxiosInstance;
	constructor(config: IConfig) {
		this.axiosInstance = axios.create(config);
		this.setupInterceptors();
	}
	/**
	 * @description: 拦截器配置
	 */
	private setupInterceptors() {
		this.axiosInstance.interceptors.request.use(
			(config) => {
				console.log(storage.get(ACCESS_TOKEN, ""));
				if(config.method?.toUpperCase() === 'POST' || config.method?.toUpperCase() === 'PATCH'){
					config["headers"]['Content-Type'] =  'application/x-www-form-urlencoded'
				}
				
				if (storage.get(ACCESS_TOKEN, "") !== "") {
					config['headers'].Authorization = storage.get(ACCESS_TOKEN, "");
					// config["token"] = 
				}
				return config;
			},
			(error) => {
				return Promise.reject(error);
			}
		);
		this.axiosInstance.interceptors.response.use(
			(response) => {
				switch (response.data.code) {
					case 200:
						if (response.data.message) {
							window['$message'].success(response.data.message);
						}
						break;
					case 401:
						window['$message'].error("登录信息已失效，请重新登录");
						router.replace({
							path: "/login",
						});
						break;
					case 400:
					case 500:
						window['$message'].error(response.data.message);
						break;
					default:
						window['$message'].info(response.data.message);
				}

				return response;
			},
			(error) => {
				// 超时处理
				let config = error.config;
				if (!config || !config.retry) {
					return Promise.reject(error);
				}
				if (error.response.data) {
					return Promise.reject({ type: "error", msg: error.response.data });
				}
				config.__retryCount = config.__retryCount || 0;

				// 如果当前发送的请求大于等于设置好的请求次数时，不再发送请求，返回最终的错误信息
				if (config.__retryCount >= config.retry) {
					if (error.message === "Network Error") {
						//message为"Network Error"代表断网了
						window['$message'].error("网络连接已断开，请检查网络");
						 return Promise.reject({
								type: "warning",
								msg: "网络连接已断开，请检查网络",
							});
					} else if (error.message === "timeout of 5000ms exceeded") {
						//网太慢了，5秒内没有接收到数据，这里的5000ms对应上方timeout设置的值
						window['$message'].error("请求超时，请检查网络");
						return Promise.reject({
							type: "warning",
							msg: "请求超时，请检查网络",
						});
					} else {
						//除以上两种以外的所有错误，包括接口报错 400 500 之类的
						window['$message'].error("出现错误，请稍后再试");
						return Promise.reject({
							type: "error",
							msg: "出现错误，请稍后再试",
						});
					}
				}

				// 记录请求次数+1
				config.__retryCount += 1;

				// 设置请求间隔 在发送下一次请求之前停留一段时间，时间为上方设置好的请求间隔时间
				var backoff = new Promise<void>(function (resolve) {
					setTimeout(function () {
						resolve();
					}, config.retryDelay || 1);
				});

				// 再次发送请求
				return backoff.then(() => {
					return this.request(config);
				});
			}
		);
	}
	/**
	 * @description:   请求方法
	 */
	request<T>(config: AxiosRequestConfig): Promise<T> {
		return new Promise((resolve, reject) => {
			this.axiosInstance
				.request<any, T>(config)
				.then((res) => {
					resolve(res);
				})
				.catch((err) => {
					reject(err);
					return err;
				});
		});
	}
	get<T>(config: AxiosRequestConfig): Promise<T> {
		return this.request<T>({ ...config, method: "GET" });
	}
	post<T>(config: AxiosRequestConfig): Promise<T> {
		return this.request<T>({ ...config, method: "POST" });
	}
	delete<T>(config: AxiosRequestConfig): Promise<T> {
		return this.request<T>({ ...config, method: "DELETE" });
	}
	patch<T>(config: AxiosRequestConfig): Promise<T> {
		return this.request<T>({ ...config, method: "PATCH" });
	}
}
export default VAxios;
